package com.example.wujinapi.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.wujinapi.comm.*;
import com.example.wujinapi.entity.*;
import com.example.wujinapi.entity.wangeditor.wangEditorJsonResult;
import com.example.wujinapi.entity.wangeditor.wangEditorUploadimageErrorJsonResult;
import com.example.wujinapi.entity.wangeditor.wangEditorUploadimageSuccessJsonResult;
import com.example.wujinapi.securityservice.SecurityLoginUser;
import com.example.wujinapi.service.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;

/**
 * 会员信息表
 *
 * @author Danie
 * @date 2020-11-17 11:25:35
 */

/*需要注意：必须使用@Controller，不能使用@RestController。
因为@RestController返回的是  JSON，且不走SpringMVC的视图解析流程，所以跳不到html那里。*/
@RestController
@Slf4j
@RequestMapping("api/")
public class ApiController {

    @Resource
    HttpServletRequest request;

    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private FirsttypeService firsttypeService;

    @Resource
    private SecondtypeService secondtypeService;

    @Resource
    private ThirdtypeService thirdtypeService;

    @Resource
    private ProductsService productsService;

    @Resource
    private ContactsService contactsService;

    @Resource
    private ProductspecificationService productspecificationService;

    @Resource
    private PcadvertisingService pcadvertisingService;



    @PostMapping(value = {"/","/adminlogin","/adminlogin.html"})
    public JsonResult adminlogin(@RequestBody Admins admins) {
        //System.out.println("传递参数"+admins);
        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(admins.getAdminname(), admins.getAdminpwd());
            Authentication authentication = authenticationManager.authenticate(authenticationToken);
            if (Objects.isNull(authentication)) {
                return new JsonResult(405, "登录失败", "用户名或密码错误");
            } else {
                //获取权限信息封装到Authentication中,后续其它过滤可调佣查询
                //存入SecurityContextHolder (让其它过滤链可以共享)
                SecurityLoginUser securityLoginUser= (SecurityLoginUser) authentication.getPrincipal();
                authenticationToken = new UsernamePasswordAuthenticationToken(securityLoginUser,null,securityLoginUser.getAthorities()); //封装权限(输入3个参数，标识位为true)
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);

                //生成jwt码
                //生成全局唯一uuid
                String sessionid = request.getSession().getId();
                Map<String,String> keys=new HashMap<String,String>();
                keys.put("sessionid",sessionid);
                String Token= jwtUtils.createToken(keys);
                log.info("当前会话id===========>" + sessionid);
                System.out.println("生成token===========>" + Token);

                /*System.out.println("开始解密token===========>");
                DecodedJWT decodedJWT=jwtUtils.getToken(Token);
                System.out.println("sessionid:"+decodedJWT.getClaim("sessionid").asString());
                System.out.println("过期时间:"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(decodedJWT.getExpiresAt()));//*/

                //保存SessionKey到Redis，并设置过期时间
                //微信小程序的sessionKey是三天后过期，必须早于此时间
                //172800=2.5(天)x24(小时)x60(分)x60(秒) (2天)
                int expireTime = Constant.expireTime; //单位：秒 默认3600秒 1小时
                //redisUtils.set("token_" + sessionid, Token, expireTime);
                Map<String,String> datas=new HashMap<String,String>();
                datas.put("token",Token);

                return new JsonResult(200, "登录成功", datas);
            }
        } catch (AuthenticationException e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
            return new JsonResult(405, "登录失败", "用户名或密码错误");
        }
    }


    //通用图片上传，返回OSS地址
    @PostMapping("/OssUploadImage")
    public JsonResult OssUploadImage(@RequestBody MultipartFile multipartFile, @RequestHeader("productNo")String productNo) {

        String uploadImageUrl="";
        try {
            System.out.println("产品编号"+productNo);

            //上传至本地服务器
            //根据产品编号生成对应的文件夹存放图片
            //String Productno=products.getProductno();
            if(!StringUtils.isEmpty(productNo)){
                String filename = multipartFile.getOriginalFilename(); //获取文件名
                String absolutePath="images/productimgs/"+productNo+"/";
                File savePos = new File("src/main/resources/static/"+absolutePath);
                if(!savePos.exists()){  // 不存在，则创建该文件夹
                    savePos.mkdir();
                }
                String destPath = savePos.getCanonicalPath()+"\\";
                filename=FileUtils.generateRandomFileName(filename); //生成唯一文件名称 xxx-xxx-xxx.jpg
                System.out.println("存放目录"+destPath);
                System.out.println("文件名"+filename);
                //上传成功返回图片地址
                uploadImageUrl=FileUtils.uploadFileToServer(multipartFile,destPath,absolutePath,filename);
            }

            //上传至阿里云
            /*String OSSimagePathName="images"; //OSS images 目录
            String uploadFileUrl= AliyunOssUtils.newUploadFile(multipartFile,OSSimagePathName);
            System.out.println("uploadFileUrl===>:"+uploadFileUrl);
            if(!StringUtils.isEmpty(uploadFileUrl)){
                //成功
                JSONObject objs=new JSONObject();
                objs.put("url",uploadFileUrl); // 图片 src ，必须
                objs.put("alt","OSS图片"); // 图片描述文字，非必须
                objs.put("href",uploadFileUrl); // 图片的链接，非必须
                return new JsonResult(200,"图片上传成功",objs);
            }*/

        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(408,"图片上传失败",e.getMessage());
        }

        return new JsonResult(200,"图片上传成功",!ObjectUtils.isEmpty(uploadImageUrl)?uploadImageUrl:null);
    }




    //WangEditor编辑器返回格式
    @PostMapping("/wangEditorUploadImage")
    public wangEditorJsonResult wangEditorUploadImage(@RequestBody MultipartFile multipartFile, @RequestHeader("productNo")String productNo) {

        String uploadImageUrl="";
        String fileOriginName= multipartFile.getOriginalFilename(); //获取文件名;文件原始名称
        try {
            System.out.println("产品编号"+productNo);

            //上传至本地服务器
            //根据产品编号生成对应的文件夹存放图片
            //String Productno=products.getProductno();
            if(!StringUtils.isEmpty(productNo)){
                String filename =fileOriginName;
                String absolutePath="images/productimgs/"+productNo+"/";
                File savePos = new File("src/main/resources/static/"+absolutePath);
                if(!savePos.exists()){  // 不存在，则创建该文件夹
                    savePos.mkdir();
                }
                String destPath = savePos.getCanonicalPath()+"\\";
                filename=FileUtils.generateRandomFileName(filename); //生成唯一文件名称 xxx-xxx-xxx.jpg
                System.out.println("存放目录"+destPath);
                System.out.println("文件名"+filename);
                //上传成功返回图片地址
                uploadImageUrl=FileUtils.uploadFileToServer(multipartFile,destPath,absolutePath,filename);
            }
        } catch (Exception e) {
            e.printStackTrace();
            /*
            * {
                "errno": 1, // 只要不等于 0 就行
                "message": "失败信息"
              }
            * */
            return new wangEditorUploadimageErrorJsonResult(408,"失败信息");
        }

        //成功
        /*if(!StringUtils.isEmpty(uploadFileUrl)){
            //成功
            JSONObject objs=new JSONObject();
            objs.put("url",uploadFileUrl); // 图片 src ，必须
            objs.put("alt","OSS图片"); // 图片描述文字，非必须
            objs.put("href",uploadFileUrl); // 图片的链接，非必须
            return new wangEditorUploadimageSuccessJsonResult(0,objs);
        }*/
        JSONObject objs=new JSONObject();
        objs.put("url",uploadImageUrl); // 图片 src ，必须
        objs.put("alt",fileOriginName); // 图片描述文字，非必须
        objs.put("href",uploadImageUrl); // 图片的链接，非必须
        return new wangEditorUploadimageSuccessJsonResult(0,objs);

    }




    /**
     * 添加一级分类
     * */
    @PostMapping("/addFirstClass")
    public JsonResult addFirstClass(@RequestBody Firsttype firsttype) {
        try {
            firsttypeService.addFirsttype(firsttype);
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(400,"添加主类失败",null);
        }
        return new JsonResult(200,"添加主类成功",null);
    }


    /**
     * 删除一级主类封面图
     * */
    @PostMapping("/deleteFirstClassById")
    public JsonResult deleteFirstClassById(@RequestBody Firsttype firsttype) {
        try {
            int dataid=firsttype.getId();
            //删除主类封面图
            Firsttype fdata=firsttypeService.getFirsttypeById(dataid);
            //读取主类图片
            String FirstClassImage=fdata.getFirstphotoface().replace(Constant.ServerIP,""); //去除http://localhost/ 截取  images/firstclassimgs/b9649186-1643-4818-b019-beb7f3178eb8.png
            //System.out.println("删除一级主类封面图:"+FirstClassImage);
            FileUtils.deleteLocalServerImage(FirstClassImage);
            //删除图片后，再删除主类
            firsttypeService.deleteFirsttype(dataid);
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(400," 删除一级分类失败",null);
        }
        return new JsonResult(200," 删除一级分类成功",null);
    }



    /**
     * 更新一级分类
     * */
    @PostMapping("/updateFirstClass")
    public JsonResult updateFirstClass(@RequestBody Firsttype firsttype) {
        try {
            firsttypeService.updateById(firsttype);
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(400,"主类更新失败",null);
        }
        return new JsonResult(200,"主类更新成功",null);
    }





    /**
     * 一级分类查询二级分类
     * */
    @PostMapping("/getSecondClass")
    public JsonResult getSecondClass(@RequestBody Firsttype Firsttype) {
        List<Secondtype> secondDatas;
        try {
            secondDatas=secondtypeService.getSecondtypesByFirstId(Firsttype.getId());
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(400,"查询分类失败",null);
        }
        return new JsonResult(200,"查询分类成功",secondDatas);
    }

    /**
     * 添加二级分类
     * */
    @PostMapping("/addSecondClass")
    public JsonResult addSecondClass(@RequestBody Secondtype secondtype) {
        try {
            secondtypeService.addSecondtype(secondtype);
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(400,"添加主类失败",null);
        }
        return new JsonResult(200,"添加主类成功",null);
    }
    /**
     * 更新二级分类
     * */
    @PostMapping("/updateSecondClass")
    public JsonResult updateSecondClass(@RequestBody Secondtype secondtype) {
        try {
            secondtypeService.updateById(secondtype);
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(400,"更新二级分类失败",null);
        }
        return new JsonResult(200,"更新二级分类成功",null);
    }
    /**
     * 删除二级分类
     * */
    @PostMapping("/deleteSecondClassById")
    public JsonResult deleteSecondClassById(@RequestBody Secondtype secondtype) {
        try {
            int dataid=secondtype.getId();
            //删除图片后，再删除主类
            secondtypeService.deleteSecondtype(dataid);
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(400," 删除二级分类分类失败",null);
        }
        return new JsonResult(200," 删除二级分类分类成功",null);
    }








    /**
     * 一级分类&二级分类  查询三级分类
     * */
    @PostMapping("/getThirdClass")
    public JsonResult getThirdClass(@RequestBody Thirdtype thirdtype) {
        List<Thirdtype> thirdDatas;
        try {
            thirdDatas=thirdtypeService.getThirdtypesByFirstIdAndSecondId(thirdtype.getFirstid(),thirdtype.getSecondid());
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(400,"查询分类失败",null);
        }
        return new JsonResult(200,"查询分类成功",thirdDatas);
    }

    /**
     * 添加三级分类
     * */
    @PostMapping("/addThirdClass")
    public JsonResult addThirdClass(@RequestBody Thirdtype thirdtype) {
        try {
            thirdtypeService.addThirdtype(thirdtype);
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(400,"添加主类失败",null);
        }
        return new JsonResult(200,"添加主类成功",null);
    }
    /**
     * 更新三级分类
     * */
    @PostMapping("/updateThirdClass")
    public JsonResult updateThirdClass(@RequestBody Thirdtype thirdtype) {
        try {
            thirdtypeService.updateById(thirdtype);
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(400,"更新三级分类失败",null);
        }
        return new JsonResult(200,"更新三级分类成功",null);
    }




    /**
     * 添加产品
     * */
    @PostMapping("/addproducts")
    public JsonResult addproducts(@RequestBody Products products) {
        try {
            productsService.addProduct(products);
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(400,"添加产品失败",null);
        }
        return new JsonResult(200,"添加产品成功",null);
    }
    /**
     * 更新产品
     * */
    @PostMapping("/updateProducts")
    public JsonResult updateProducts(@RequestBody Products products) {
        try {
            productsService.updateProduct(products);
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(400,"添加产品失败",null);
        }
        return new JsonResult(200,"添加产品成功",null);
    }
    /**
     * 删除产品
     * */
    @PostMapping("/deleteProductById")
    public JsonResult deleteProductById(@RequestBody Products products) {
        try {

            //获取当前产品id
            int dataid=products.getId();
            Products productinfo=productsService.getProductById(dataid);
            System.out.println("当前产品id"+dataid);
            /*
            System.out.println("当前产品信息"+productinfo);*/

            //删除封面图
            String productFaceImage=productinfo.getProductimg();
            if(!StringUtils.isEmpty(productFaceImage)){
                System.out.println("当前产品封面图:"+productFaceImage);
                //删除封面图
                FileUtils.deleteLocalServerImage(productFaceImage);
            }


            //删除产品详情图
            String imgsData=productinfo.getProductdetailsimg();
            if(!StringUtils.isEmpty(imgsData)){
                ObjectMapper objectMapper=new ObjectMapper();
                String[] productDetailsImage=objectMapper.readValue(imgsData,String[].class);
                for (int i = 0; i < productDetailsImage.length; i++) {
                    System.out.println("当前产品详情图:"+productDetailsImage[i]);
                    //删除每一张图片
                    FileUtils.deleteLocalServerImage(productDetailsImage[i]);
                }
            }

            //删除产品数据
            productsService.deleteProduct(dataid);

        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(400,"删除产品失败",null);
        }
        return new JsonResult(200,"删除产品成功",null);
    }


    //主类封面图上传
    @PostMapping("/FirstClassUploadImage")
    public JsonResult FirstClassUploadImage(@RequestBody MultipartFile multipartFile) {
        String uploadImageUrl="";
        try {
                //上传至本地服务器
                String filename = multipartFile.getOriginalFilename(); //获取文件名
                String absolutePath="images/firstclassimgs/";
                File savePos = new File("src/main/resources/static/"+absolutePath);
                if(!savePos.exists()){  // 不存在，则创建该文件夹
                    savePos.mkdir();
                }
                String destPath = savePos.getCanonicalPath()+"\\";
                filename=FileUtils.generateRandomFileName(filename); //生成唯一文件名称 xxx-xxx-xxx.jpg
                System.out.println("存放目录"+destPath);
                System.out.println("文件名"+filename);
                //上传成功返回图片地址
                uploadImageUrl=FileUtils.uploadFileToServer(multipartFile,destPath,absolutePath,filename);
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(408,"图片上传失败",e.getMessage());
        }
        return new JsonResult(200,"图片上传成功",!ObjectUtils.isEmpty(uploadImageUrl)?uploadImageUrl:null);
    }

    //主类图更新
    @PostMapping("/SyncFirstClassAjaxRequestById")
    public JsonResult SyncFirstClassAjaxRequestById(@RequestBody MultipartFile multipartFile, @RequestHeader("firstClassId") String firstClassId) {
        if(!StringUtils.isEmpty(firstClassId)){
            String uploadImageUrl="";
            try {
                //上传至本地服务器
                String filename = multipartFile.getOriginalFilename(); //获取文件名
                String absolutePath="images/firstclassimgs/";
                File savePos = new File("src/main/resources/static/"+absolutePath);
                if(!savePos.exists()){  // 不存在，则创建该文件夹
                    savePos.mkdir();
                }
                String destPath = savePos.getCanonicalPath()+"\\";
                filename=FileUtils.generateRandomFileName(filename); //生成唯一文件名称 xxx-xxx-xxx.jpg
                System.out.println("存放目录"+destPath);
                System.out.println("文件名"+filename);
                //上传成功返回图片地址
                uploadImageUrl=FileUtils.uploadFileToServer(multipartFile,destPath,absolutePath,filename);

                //更新数据库
                Firsttype firsttype=new Firsttype();
                firsttype.setId(Integer.valueOf(firstClassId));
                firsttype.setFirstphotoface(uploadImageUrl); //更改图片地址
                firsttypeService.updateFirsttype(firsttype);

            } catch (Exception e) {
                e.printStackTrace();
                return new JsonResult(408,"图片上传失败",e.getMessage());
            }
            return new JsonResult(200,"图片上传成功",!ObjectUtils.isEmpty(uploadImageUrl)?uploadImageUrl:null);
        }else{
            return new JsonResult(408,"图片上传失败","图片id异常");
        }

    }


    /**
     * 添加联系方式内容
     * */
    @PostMapping("/addContacts")
    public JsonResult addContacts(@RequestBody Contacts contacts) {
        try {
            contactsService.addContacts(contacts);
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(400,"添加联系方式内容失败",null);
        }
        return new JsonResult(200,"添加联系方式内容成功",null);
    }





    /**
     * 添加产品规格
     * */
    @PostMapping("/addProductSpecification")
    public JsonResult addProductSpecification(@RequestBody Productspecification productspecification) {
        try {
            productspecificationService.addProductspecification(productspecification);
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(400,"添加产品规格失败",null);
        }
        return new JsonResult(200,"添加产品规格成功",null);
    }
    /**
     * 更新产品规格
     * */
    @PostMapping("/updateProductSpecification")
    public JsonResult updateProductSpecification(@RequestBody Productspecification productspecification) {
        try {
            if(!Objects.isNull(productspecification.getId())) {
                productspecificationService.updateProductspecification(productspecification);
            }else{
                System.out.println("规则id不存在");
                return new JsonResult(400,"更新产品规格","规则id不存在");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(400,"主类更新失败",null);
        }
        return new JsonResult(200,"主类更新成功",null);
    }
    /**
     * 删除产品规格
     * */
    @PostMapping("/deleteProductSpecificationById")
    public JsonResult deleteProductSpecificationById(@RequestBody Productspecification productspecification) {
        try {
            int dataid=productspecification.getId();
            //删除图片后，再删除主类
            productspecificationService.deleteProductspecification(dataid);
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(400," 删除二级分类分类失败",null);
        }
        return new JsonResult(200," 删除二级分类分类成功",null);
    }




    //更新首页广告
    @PostMapping("/updateHomeAdvertising")
    public JsonResult updateHomeAdvertising(@RequestBody Pcadvertising pcadvertising){
        try {
            int rct=pcadvertisingService.UpdatePcad(pcadvertising);
            if(rct==0){
                new JsonResult(200,"首页广告更新成功",null);
            }else{
                new JsonResult(404,"首页广告更新失败",null);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new JsonResult(200,"更新首页广告更新成功",null);
    }


} // Class End
